package com.iflytek.uoamp.notify.wechat.plugins;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.uoamp.common.notify.constant.ConstField;
import com.iflytek.uoamp.common.notify.enumerate.ContactState;
import com.iflytek.uoamp.common.notify.enumerate.ContentType;
import com.iflytek.uoamp.common.notify.format.Formatter;
import com.iflytek.uoamp.common.notify.obj.Contact;
import com.iflytek.uoamp.common.notify.plugins.AbstractPlugin;
import com.iflytek.uoamp.common.notify.util.LogbackInstance;
import com.iflytek.uoamp.notify.wechat.format.FormatFocusWechat;
import com.iflytek.uoamp.notify.wechat.format.FormatWechatFactory;
import com.iflytek.uoamp.notify.wechat.format.WechatFormatter;
import com.iflytek.uoamp.notify.wechat.main.Notification;
import com.iflytek.uoamp.notify.wechat.main.SendMsg;
import com.iflytek.uoamp.notify.wechat.vo.MsgInfo;

public class WechatPlugin extends AbstractPlugin{
	
	private static final Logger logger = LogbackInstance.getInstance().getLogger(WechatPlugin.class);
	
	@Override
	public Formatter getFormatter() {
	    if(formatter != null) {
	        return formatter;
	    }
	    
		if(useTemplate) {
          if (notification.getExtend().containsKey(ConstField.FOCUS_WARN_FLAG)) {
              formatter = new FormatFocusWechat();
          } else {
              ContentType type = ContentType.getType(notification.getContentType());
              formatter = FormatWechatFactory.getMsgFormatter(type);
          }

		} else {
			formatter = new WechatFormatter();
		}
		
		return formatter;
	}

	@Override
	public boolean sendContent(String content, List<Contact> contacts) {
		boolean ignored = true;
	    boolean ret = true;
	    
	    for (Contact contact : contacts) {
	    	ignored = false;
	    	try {
	    		List<String> phone = new ArrayList<String>();
	    		if(StringUtils.isNotEmpty(contact.getPhone())){//不为空发送，为空直接丢弃
	    			phone.add(contact.getPhone());
                  
	    			Notification notification = new Notification();
	    			notification.setContacts(phone);
	    			notification.setContent(content);
	    			sendWx(notification);
                  
	    			setState(contacts, ContactState.SUCCESS);
	    			logInfo.addInfo(MessageFormat.format(ConstField.SENDINGMSG, formatter.getContent(content), contact.getPhone()));
	    		}
	    		ret &= true;
	    	} catch (Exception e) {
	    		setState(contacts, ContactState.FAILED);
	    		logInfo.addError(e.getMessage());
	    		ret &= false;
	    	}
	    }

	    if (ignored) {
	    	logInfo.addError(MessageFormat.format(ConstField.DISABLEPLUGIN, "msg", ConstField.NOPROPERCONTACTS));
	    	return false;
	    }
      
	    return ret;
	}
	
	
	public void sendWx(Notification notification) throws Exception {
		if (notification == null) {
			return ;
		}
		String content = notification.getContent().replaceAll("&quot;", "\"");
		List<String> openIds = notification.getContacts();
		int pos = content.indexOf("@@");
		if (pos != -1) {
			String text = content.substring(pos + "@@".length());
			JSONObject obj=JSONObject.parseObject(text);
			MsgInfo msgInfo = new MsgInfo();
			msgInfo.setContent(obj.getString("statedes"));//内容
			msgInfo.setTitle(obj.getString("monitorname"));//标题
			msgInfo.setTime(obj.getString("monitortime"));//时间
			for (Iterator<String> localIterator = openIds.iterator(); localIterator.hasNext();) {
				String openId = (String) localIterator.next();
				logger.info("send wx =============================="+"openId:"+openId);
				SendMsg.send_template_message(openId, msgInfo);
			}
		}else{
			throw new IllegalArgumentException("发送内容格式不正确.");
		}
	}
}